@echo off
setlocal enabledelayedexpansion

if "%~1"=="" (
    echo Usage: %0 [directory_path]
    echo Example: %0 "D:\myfolder"
    pause
    exit /b
)

set "target_dir=%~1"
echo Counting lines in .txt files in: !target_dir!
echo.

set total=0
set count=0
set error_count=0

if not exist "!target_dir!" (
    echo Error: Directory "!target_dir!" does not exist.
    pause
    exit /b
)

:: 创建临时文件列表
set "tempfile=%temp%\filelist_%random%.txt"
dir /b /a-d "!target_dir!\*.txt" > "!tempfile!" 2>nul

:: 处理每个文件
for /f "usebackq delims=" %%f in ("!tempfile!") do (
    set "filepath=!target_dir!\%%f"
    set "lines=0"
    set "read_error=0"

    :: 尝试读取文件
    for /f %%i in ('type "!filepath!" 2^>nul ^| find /c /v "" 2^>nul') do (
        set "lines=%%i"
    )

    :: 检查是否成功读取
    if "!lines!"=="0" (
        echo 无法读取文件: %%f
        set /a error_count+=1
    ) else (
@REM         echo Processing: %%f - !lines! lines
        set /a total+=!lines!
        set /a count+=1
    )
)

:: 清理临时文件
if exist "!tempfile!" del "!tempfile!"

echo.
echo Files processed successfully: !count!
echo Files with read errors: !error_count!
echo Total lines: !total!
pause
